"""
city_game_final.py - 城市建造游戏 (最终版)
独立运行的游戏主程序，不依赖g4f
使用预先生成的本地图标文件
"""

import json
import os
import time
from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.parse
import threading
import sys

class CityBuilder:
    """
    城市建造游戏核心类 (不依赖g4f)
    """
    
    def __init__(self, db_file="city_data.json", html_file="city_game.html", port=8086):
        """
        初始化城市建造游戏
        
        Args:
            db_file: 游戏数据文件
            html_file: 游戏界面文件
            port: 服务器端口
        """
        # 创建游戏目录
        self.game_dir = "pgame"
        self.icons_dir = os.path.join(self.game_dir, "icons")
        
        # 验证图标文件
        if not self.verify_icon_files():
            print("错误: 缺少图标文件，请先运行 icon_generator.py 生成图标")
            print("或确保 'pgame/icons/' 目录包含所有图标文件")
            sys.exit(1)
        
        # 初始化游戏数据
        self.city_size = 10
        self.game_state = "main"
        self.selected_type = ""
        self.init_game_data()
        
        print("✓ 游戏初始化完成")
        print(f"✓ 图标目录: {self.icons_dir}")
    
    def verify_icon_files(self):
        """验证所有图标文件是否存在"""
        required_icons = ["road.png", "house.png", "commercial.png", 
                         "industrial.png", "park.png", "empty.png"]
        
        # 创建目录如果不存在
        os.makedirs(self.icons_dir, exist_ok=True)
        
        missing_icons = []
        for icon in required_icons:
            icon_path = os.path.join(self.icons_dir, icon)
            if not os.path.exists(icon_path):
                missing_icons.append(icon)
        
        if missing_icons:
            print(f"缺少图标文件: {', '.join(missing_icons)}")
            return False
        
        return True
    
    def init_game_data(self):
        """初始化游戏数据"""
        # 检查是否已经有游戏数据
        try:
            if os.path.exists("city_data.json"):
                with open("city_data.json", "r", encoding="utf-8") as f:
                    data = json.load(f)
                if data:
                    print("✓ 使用现有游戏数据")
                    return
        except:
            pass
        
        # 初始化新的游戏数据
        game_data = {
            "game_state": "main",
            "selected_type": "",
            "city_map": self.create_empty_map(),
            "resources": {
                "money": 1000,
                "roads": 20,
                "buildings": 10
            },
            "stats": {
                "total_roads": 0,
                "total_buildings": 0,
                "last_update": time.time()
            }
        }
        
        # 添加一些初始道路和建筑作为示例
        map_data = game_data["city_map"]
        
        # 添加一条主路
        for i in range(3, 7):
            map_data[5][i] = "R"  # 道路
        
        # 添加一些建筑
        map_data[2][2] = "H"  # 住宅
        map_data[2][7] = "C"  # 商业
        map_data[7][2] = "I"  # 工业
        map_data[7][7] = "P"  # 公园
        
        # 保存游戏数据
        with open("city_data.json", "w", encoding="utf-8") as f:
            json.dump(game_data, f, ensure_ascii=False, indent=2)
        
        print("✓ 游戏数据已初始化")
    
    def create_empty_map(self):
        """创建空的城市地图"""
        return [["" for _ in range(self.city_size)] for _ in range(self.city_size)]
    
    def get_game_data(self):
        """获取游戏数据"""
        try:
            with open("city_data.json", "r", encoding="utf-8") as f:
                return json.load(f)
        except:
            return None
    
    def save_game_data(self, game_data):
        """保存游戏数据"""
        with open("city_data.json", "w", encoding="utf-8") as f:
            json.dump(game_data, f, ensure_ascii=False, indent=2)
    
    def update_game_state(self, new_state):
        """更新游戏状态"""
        game_data = self.get_game_data()
        if game_data:
            game_data["game_state"] = new_state
            self.save_game_data(game_data)
            self.game_state = new_state
            return True
        return False
    
    def get_icon_path(self, building_type):
        """根据建筑类型获取图标路径"""
        icon_map = {
            "R": "road.png",
            "H": "house.png",
            "C": "commercial.png",
            "I": "industrial.png",
            "P": "park.png",
            "": "empty.png"
        }
        
        filename = icon_map.get(building_type, "empty.png")
        return f"{self.game_dir}/icons/{filename}"
    
    def get_building_name(self, building_type):
        """获取建筑类型名称"""
        names = {
            "R": "道路",
            "H": "住宅",
            "C": "商业",
            "I": "工业",
            "P": "公园"
        }
        return names.get(building_type, "未知")
    
    def build_at(self, x, y, building_type=None):
        """在指定位置建造"""
        game_data = self.get_game_data()
        if not game_data:
            return False
        
        # 使用传入的类型或当前选择的类型
        build_type = building_type or game_data.get("selected_type", "")
        
        if not build_type:
            return False
        
        # 检查位置是否有效
        if not (0 <= x < self.city_size and 0 <= y < self.city_size):
            return False
        
        # 检查资源
        resources = game_data["resources"]
        
        if build_type == "R":  # 道路
            if resources["roads"] <= 0:
                return False
            resources["roads"] -= 1
            game_data["stats"]["total_roads"] += 1
        
        elif build_type in ["H", "C", "I", "P"]:  # 各种建筑
            if resources["buildings"] <= 0:
                return False
            resources["buildings"] -= 1
            game_data["stats"]["total_buildings"] += 1
            resources["money"] -= 10
        
        # 更新地图
        game_data["city_map"][y][x] = build_type
        
        # 增加金钱收入
        if build_type == "H":
            resources["money"] += 5
        elif build_type == "C":
            resources["money"] += 10
        elif build_type == "I":
            resources["money"] += 7
        
        # 更新时间戳
        game_data["stats"]["last_update"] = time.time()
        
        self.save_game_data(game_data)
        return True
    
    def clear_at(self, x, y):
        """清除指定位置的建筑"""
        game_data = self.get_game_data()
        if not game_data:
            return False
        
        if not (0 <= x < self.city_size and 0 <= y < self.city_size):
            return False
        
        # 获取当前位置的建筑类型
        current_type = game_data["city_map"][y][x]
        
        # 返还资源
        if current_type == "R":
            game_data["resources"]["roads"] += 1
            game_data["stats"]["total_roads"] = max(0, game_data["stats"]["total_roads"] - 1)
        elif current_type in ["H", "C", "I", "P"]:
            game_data["resources"]["buildings"] += 1
            game_data["stats"]["total_buildings"] = max(0, game_data["stats"]["total_buildings"] - 1)
        
        # 清除地图位置
        game_data["city_map"][y][x] = ""
        
        # 更新时间戳
        game_data["stats"]["last_update"] = time.time()
        
        self.save_game_data(game_data)
        return True
    
    def get_city_map_html(self):
        """生成城市地图的HTML"""
        game_data = self.get_game_data()
        if not game_data:
            return ""
        
        city_map = game_data["city_map"]
        
        html = ['<div class="city-map">']
        
        for y in range(self.city_size):
            html.append('<div class="map-row">')
            for x in range(self.city_size):
                cell_type = city_map[y][x]
                cell_class = "map-cell"
                
                # 获取图标路径
                icon_path = self.get_icon_path(cell_type)
                
                # 创建单元格
                html.append(f'<button class="{cell_class}" onclick="buildAt({x}, {y})" ')
                html.append(f'title="位置: ({x}, {y})">')
                html.append(f'<img src="{icon_path}" alt="{cell_type}" class="cell-img"></button>')
            
            html.append('</div>')
        
        html.append('</div>')
        return ''.join(html)
    
    def get_resources_html(self):
        """生成资源显示的HTML"""
        game_data = self.get_game_data()
        if not game_data:
            return ""
        
        resources = game_data["resources"]
        
        html = []
        html.append('<div class="resources-display">')
        html.append(f'<span class="resource-item">💰 {resources["money"]}</span>')
        html.append(f'<span class="resource-item"><img src="{self.get_icon_path("R")}" alt="⬛️" class="resource-icon"> {resources["roads"]}</span>')
        html.append(f'<span class="resource-item"><img src="{self.get_icon_path("C")}" alt="🏢" class="resource-icon"> {resources["buildings"]}</span>')
        html.append('</div>')
        return ''.join(html)
    
    def create_game_html(self):
        """创建游戏HTML页面"""
        game_data = self.get_game_data()
        if not game_data:
            game_state = "main"
        else:
            game_state = game_data.get("game_state", "main")
        
        # 创建完整的HTML页面
        html = f'''<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>城市建造游戏</title>
    <style>
        * {{
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }}
        
        body {{
            font-family: 'Arial', sans-serif;
            background: #2c3e50;
            min-height: 100vh;
            padding: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
        }}
        
        .game-container {{
            background: #34495e;
            border: 2px solid #1a252f;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            max-width: 500px;
            width: 100%;
        }}
        
        .game-header {{
            background: #1a252f;
            color: white;
            padding: 8px 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 2px solid #34495e;
        }}
        
        .game-title {{
            font-size: 1.1em;
            font-weight: bold;
            color: #ecf0f1;
        }}
        
        .resources-display {{
            display: flex;
            gap: 15px;
            font-size: 0.9em;
        }}
        
        .resource-item {{
            display: flex;
            align-items: center;
            gap: 4px;
            color: #ecf0f1;
            background: rgba(255,255,255,0.1);
            padding: 4px 8px;
            border-radius: 3px;
        }}
        
        .resource-icon {{
            width: 16px;
            height: 16px;
            display: block;
        }}
        
        .nav-buttons {{
            display: flex;
            border-bottom: 2px solid #1a252f;
            background: #2c3e50;
        }}
        
        .nav-btn {{
            flex: 1;
            padding: 10px 5px;
            border: none;
            background: transparent;
            color: #ecf0f1;
            cursor: pointer;
            font-size: 0.85em;
            text-align: center;
            border-right: 1px solid #1a252f;
            transition: all 0.2s;
        }}
        
        .nav-btn:last-child {{
            border-right: none;
        }}
        
        .nav-btn:hover {{
            background: rgba(255,255,255,0.1);
        }}
        
        .nav-btn.active {{
            background: #3498db;
            color: white;
            font-weight: bold;
        }}
        
        .game-content {{
            padding: 12px;
            background: #2c3e50;
        }}
        
        .mode-title {{
            color: #ecf0f1;
            font-size: 0.95em;
            margin-bottom: 10px;
            text-align: center;
            padding: 5px;
            background: rgba(0,0,0,0.2);
            border-radius: 3px;
        }}
        
        .city-map {{
            display: flex;
            flex-direction: column;
            gap: 0;
            margin: 0 auto;
            width: fit-content;
            border: 1px solid #1a252f;
            background: #1a252f;
        }}
        
        .map-row {{
            display: flex;
            gap: 0;
        }}
        
        .map-cell {{
            width: 30px;
            height: 30px;
            border: 1px solid #2c3e50;
            background: #34495e;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.1s;
            margin: 0;
            padding: 0;
            border-radius: 0;
        }}
        
        .map-cell:hover {{
            background: #4a6572;
            transform: scale(1.05);
            z-index: 1;
            position: relative;
        }}
        
        .cell-img {{
            width: 24px;
            height: 24px;
            display: block;
            pointer-events: none;
        }}
        
        .building-types {{
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 8px;
            margin: 12px 0;
        }}
        
        .building-btn {{
            padding: 10px 5px;
            border: 2px solid #1a252f;
            background: #34495e;
            cursor: pointer;
            border-radius: 0;
            transition: all 0.2s;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
        }}
        
        .building-btn:hover {{
            background: #4a6572;
            border-color: #3498db;
        }}
        
        .building-img {{
            width: 32px;
            height: 32px;
            display: block;
        }}
        
        .building-name {{
            font-size: 0.8em;
            font-weight: bold;
            color: #ecf0f1;
        }}
        
        .building-desc {{
            font-size: 0.7em;
            color: #bdc3c7;
        }}
        
        .status-message {{
            position: fixed;
            top: 10px;
            right: 10px;
            padding: 8px 12px;
            background: #27ae60;
            color: white;
            font-weight: bold;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
            opacity: 0;
            transform: translateY(-20px);
            transition: all 0.3s ease;
            z-index: 1000;
            border-radius: 3px;
        }}
        
        .status-message.show {{
            opacity: 1;
            transform: translateY(0);
        }}
        
        .status-message.error {{
            background: #e74c3c;
        }}
        
        .clear-btn {{
            background: #e74c3c;
            color: white;
            border: none;
            padding: 10px;
            cursor: pointer;
            font-weight: bold;
            margin-top: 15px;
            width: 100%;
            border-radius: 0;
            transition: background 0.2s;
        }}
        
        .clear-btn:hover {{
            background: #c0392b;
        }}
        
        .instructions {{
            background: #1a252f;
            border: 1px solid #34495e;
            padding: 10px;
            margin-top: 15px;
            font-size: 0.8em;
            color: #bdc3c7;
            border-radius: 3px;
        }}
        
        .instructions-title {{
            font-weight: bold;
            margin-bottom: 5px;
            color: #ecf0f1;
            font-size: 0.9em;
        }}
        
        .instructions-list {{
            margin-left: 15px;
        }}
        
        .instructions-list li {{
            margin-bottom: 3px;
        }}
        
        @media (max-width: 400px) {{
            .map-cell {{
                width: 28px;
                height: 28px;
            }}
            
            .cell-img {{
                width: 22px;
                height: 22px;
            }}
            
            .game-header {{
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }}
            
            .resources-display {{
                width: 100%;
                justify-content: space-between;
            }}
        }}
    </style>
</head>
<body>
    <div class="game-container">
        <div class="game-header">
            <div class="game-title">城市建造游戏</div>
            {self.get_resources_html()}
        </div>
        
        <div class="nav-buttons">
            <button class="nav-btn {'active' if game_state == 'main' else ''}" onclick="goToMain()">
                主页
            </button>
            <button class="nav-btn {'active' if game_state == 'build_road' else ''}" onclick="goToRoad()">
                道路
            </button>
            <button class="nav-btn {'active' if game_state == 'build_building' or game_state.startswith('build_') else ''}" onclick="goToBuilding()">
                建筑
            </button>
        </div>
        
        <div class="game-content">
        '''
        
        # 根据游戏状态添加内容
        if game_state == "main":
            html += f'''
            <div class="mode-title">城市规划图</div>
            {self.get_city_map_html()}
            <div class="instructions">
                <div class="instructions-title">游戏说明</div>
                <ul class="instructions-list">
                    <li>点击上方按钮切换建造模式</li>
                    <li>点击地图格子建造或清除建筑</li>
                    <li>不同建筑有不同的效果和成本</li>
                    <li>资源不足时无法建造</li>
                </ul>
            </div>
            <button class="clear-btn" onclick="clearAll()">清除所有建筑</button>
            '''
        elif game_state == "build_road":
            html += f'''
            <div class="mode-title">建造模式: 道路 <img src="{self.get_icon_path('R')}" alt="⬛️" style="width:20px;height:20px;vertical-align:middle;margin-left:5px;"></div>
            {self.get_city_map_html()}
            <div class="instructions">
                <div class="instructions-title">道路说明</div>
                <ul class="instructions-list">
                    <li>点击空地建造道路 (消耗1道路资源)</li>
                    <li>点击已有建筑清除并返还资源</li>
                    <li>道路不产生收入，但连接建筑</li>
                </ul>
            </div>
            '''
        elif game_state == "build_building":
            html += f'''
            <div class="mode-title">选择建筑类型</div>
            <div class="building-types">
                <button class="building-btn" onclick="selectBuilding('house')">
                    <img src="{self.get_icon_path('H')}" alt="🏠" class="building-img">
                    <span class="building-name">住宅</span>
                    <span class="building-desc">+5资金/成本10</span>
                </button>
                <button class="building-btn" onclick="selectBuilding('commercial')">
                    <img src="{self.get_icon_path('C')}" alt="🏢" class="building-img">
                    <span class="building-name">商业</span>
                    <span class="building-desc">+10资金/成本10</span>
                </button>
                <button class="building-btn" onclick="selectBuilding('industrial')">
                    <img src="{self.get_icon_path('I')}" alt="🏭" class="building-img">
                    <span class="building-name">工业</span>
                    <span class="building-desc">+7资金/成本10</span>
                </button>
                <button class="building-btn" onclick="selectBuilding('park')">
                    <img src="{self.get_icon_path('P')}" alt="🎪" class="building-img">
                    <span class="building-name">公园</span>
                    <span class="building-desc">美化环境/成本10</span>
                </button>
            </div>
            <div class="instructions">
                <div class="instructions-title">建筑说明</div>
                <ul class="instructions-list">
                    <li>选择一种建筑类型进行建造</li>
                    <li>每种建筑有不同的收入和效果</li>
                    <li>建筑需要消耗资金和建筑资源</li>
                </ul>
            </div>
            '''
        elif game_state.startswith("build_"):
            building_type = game_state[6:].upper()
            building_name = self.get_building_name(building_type)
            
            html += f'''
            <div class="mode-title">建造模式: {building_name} <img src="{self.get_icon_path(building_type)}" alt="{building_type}" style="width:20px;height:20px;vertical-align:middle;margin-left:5px;"></div>
            {self.get_city_map_html()}
            <div class="instructions">
                <div class="instructions-title">{building_name}说明</div>
                <ul class="instructions-list">
                    <li>点击空地建造{building_name} (消耗1建筑资源+10资金)</li>
                    <li>点击已有建筑清除并返还资源</li>
            '''
            
            if building_type == "H":
                html += '<li>住宅: 每回合产生5资金</li>'
            elif building_type == "C":
                html += '<li>商业: 每回合产生10资金</li>'
            elif building_type == "I":
                html += '<li>工业: 每回合产生7资金</li>'
            elif building_type == "P":
                html += '<li>公园: 美化环境，不产生收入</li>'
            
            html += '''
                </ul>
            </div>
            '''
        
        html += '''
        </div>
    </div>
    
    <div id="statusMessage" class="status-message"></div>
    
    <script>
        // 显示状态消息
        function showStatus(message, isError = false) {
            const statusDiv = document.getElementById('statusMessage');
            statusDiv.textContent = message;
            statusDiv.className = 'status-message' + (isError ? ' error' : '');
            statusDiv.classList.add('show');
            
            setTimeout(() => {
                statusDiv.classList.remove('show');
            }, 2000);
        }
        
        // 导航函数
        function goToMain() {
            updateGameState('main');
        }
        
        function goToRoad() {
            updateGameState('build_road');
        }
        
        function goToBuilding() {
            updateGameState('build_building');
        }
        
        function selectBuilding(type) {
            updateGameState('build_' + type.toLowerCase());
        }
        
        // 更新游戏状态
        async function updateGameState(newState) {
            try {
                const response = await fetch('/api/update_state', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ state: newState })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    window.location.reload();
                } else {
                    showStatus('操作失败: ' + result.message, true);
                }
            } catch (error) {
                showStatus('网络错误: ' + error.message, true);
            }
        }
        
        // 建造函数
        async function buildAt(x, y) {
            try {
                const response = await fetch('/api/build', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ x: x, y: y })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showStatus('操作成功!');
                    setTimeout(() => {
                        window.location.reload();
                    }, 300);
                } else {
                    showStatus('操作失败: ' + result.message, true);
                }
            } catch (error) {
                showStatus('网络错误: ' + error.message, true);
            }
        }
        
        // 清除所有建筑
        async function clearAll() {
            if (!confirm('确定要清除所有建筑吗？这将返还所有资源。')) {
                return;
            }
            
            try {
                const response = await fetch('/api/clear_all', {
                    method: 'POST'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showStatus('已清除所有建筑');
                    setTimeout(() => {
                        window.location.reload();
                    }, 300);
                } else {
                    showStatus('清除失败: ' + result.message, true);
                }
            } catch (error) {
                showStatus('网络错误: ' + error.message, true);
            }
        }
        
        // 自动保存
        function autoSave() {
            fetch('/api/save');
        }
        
        // 每30秒自动保存一次
        setInterval(autoSave, 30000);
    </script>
</body>
</html>'''
        
        return html
    
    def clear_all_buildings(self):
        """清除所有建筑"""
        game_data = self.get_game_data()
        if not game_data:
            return False
        
        city_map = game_data["city_map"]
        for y in range(self.city_size):
            for x in range(self.city_size):
                current_type = city_map[y][x]
                
                if current_type == "R":
                    game_data["resources"]["roads"] += 1
                    game_data["stats"]["total_roads"] = max(0, game_data["stats"]["total_roads"] - 1)
                elif current_type in ["H", "C", "I", "P"]:
                    game_data["resources"]["buildings"] += 1
                    game_data["stats"]["total_buildings"] = max(0, game_data["stats"]["total_buildings"] - 1)
                
                city_map[y][x] = ""
        
        game_data["stats"]["last_update"] = time.time()
        
        self.save_game_data(game_data)
        return True


class CityGameRequestHandler(BaseHTTPRequestHandler):
    """游戏HTTP请求处理器"""
    
    def __init__(self, *args, **kwargs):
        self.game = kwargs.pop('game_instance', None)
        super().__init__(*args, **kwargs)
    
    def _set_headers(self, status_code=200, content_type='application/json'):
        """设置HTTP响应头"""
        self.send_response(status_code)
        self.send_header('Content-type', content_type)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
    
    def do_GET(self):
        """处理GET请求"""
        parsed_path = urllib.parse.urlparse(self.path)
        
        if parsed_path.path == '/' or parsed_path.path == '/index.html':
            # 返回游戏主页面
            self.send_response(200)
            self.send_header('Content-type', 'text/html; charset=utf-8')
            self.end_headers()
            
            html_content = self.game.create_game_html()
            self.wfile.write(html_content.encode('utf-8'))
        
        elif parsed_path.path.startswith('/pgame/'):
            # 提供静态文件（图标等）
            try:
                file_path = parsed_path.path[1:]
                if os.path.exists(file_path):
                    with open(file_path, 'rb') as f:
                        content = f.read()
                    
                    self.send_response(200)
                    if file_path.endswith('.png'):
                        self.send_header('Content-type', 'image/png')
                    elif file_path.endswith('.html'):
                        self.send_header('Content-type', 'text/html')
                    else:
                        self.send_header('Content-type', 'application/octet-stream')
                    
                    self.end_headers()
                    self.wfile.write(content)
                else:
                    self.send_response(404)
                    self.end_headers()
            except Exception as e:
                self.send_response(500)
                self.end_headers()
        
        elif parsed_path.path == '/api/game_data':
            # 返回游戏数据
            self._set_headers(200)
            game_data = self.game.get_game_data()
            self.wfile.write(json.dumps(game_data).encode('utf-8'))
        
        else:
            self._set_headers(404)
            self.wfile.write(json.dumps({'error': 'Not found'}).encode())
    
    def do_POST(self):
        """处理POST请求"""
        parsed_path = urllib.parse.urlparse(self.path)
        
        # 获取请求体数据
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        
        try:
            data = json.loads(post_data.decode('utf-8'))
        except:
            data = {}
        
        response = {"success": False, "message": "未知操作"}
        
        if parsed_path.path == '/api/update_state':
            new_state = data.get('state', 'main')
            if self.game.update_game_state(new_state):
                response = {"success": True, "message": "状态已更新"}
            else:
                response = {"success": False, "message": "状态更新失败"}
        
        elif parsed_path.path == '/api/build':
            x = data.get('x', 0)
            y = data.get('y', 0)
            
            game_data = self.game.get_game_data()
            if not game_data:
                response = {"success": False, "message": "游戏数据加载失败"}
            else:
                game_state = game_data.get("game_state", "main")
                
                if game_state.startswith("build_"):
                    if game_state == "build_road":
                        build_type = "R"
                    elif game_state == "build_building":
                        response = {"success": False, "message": "请先选择建筑类型"}
                    else:
                        building_type = game_state[6:].upper()
                        build_type = building_type[0] if building_type else ""
                    
                    if build_type:
                        existing_type = game_data["city_map"][y][x] if 0 <= y < len(game_data["city_map"]) and 0 <= x < len(game_data["city_map"][0]) else ""
                        
                        if existing_type:
                            if self.game.clear_at(x, y):
                                building_name = self.game.get_building_name(existing_type)
                                response = {"success": True, "message": f"已清除{building_name}"}
                            else:
                                response = {"success": False, "message": "清除失败"}
                        else:
                            if self.game.build_at(x, y, build_type):
                                building_name = self.game.get_building_name(build_type)
                                response = {"success": True, "message": f"建造{building_name}成功"}
                            else:
                                response = {"success": False, "message": "建造失败，资源不足"}
                    else:
                        response = {"success": False, "message": "未知的建筑类型"}
                else:
                    response = {"success": False, "message": "不在建造模式"}
        
        elif parsed_path.path == '/api/clear_all':
            if self.game.clear_all_buildings():
                response = {"success": True, "message": "已清除所有建筑"}
            else:
                response = {"success": False, "message": "清除失败"}
        
        elif parsed_path.path == '/api/save':
            game_data = self.game.get_game_data()
            if game_data:
                self.game.save_game_data(game_data)
                response = {"success": True, "message": "游戏已保存"}
            else:
                response = {"success": False, "message": "保存失败"}
        
        self._set_headers(200)
        self.wfile.write(json.dumps(response).encode('utf-8'))
    
    def log_message(self, format, *args):
        """简化日志输出"""
        pass


class CityGameServer:
    """游戏服务器"""
    
    def __init__(self, port=8086):
        self.port = port
        self.city_builder = CityBuilder(port=port)
        self.server = None
    
    def start(self, background=False):
        """启动游戏服务器"""
        server_address = ('', self.port)
        
        def handler_factory(*args, **kwargs):
            return CityGameRequestHandler(*args, **kwargs, game_instance=self.city_builder)
        
        self.server = HTTPServer(server_address, handler_factory)
        
        print("=" * 50)
        print("城市建造游戏 (最终版)")
        print("=" * 50)
        print(f"游戏地址: http://localhost:{self.port}")
        print(f"游戏数据: city_data.json")
        print(f"图标目录: pgame/icons/")
        print("=" * 50)
        print("游戏功能:")
        print("  • 主页: 查看城市概览")
        print("  • 道路: 建造道路 (消耗道路资源)")
        print("  • 建筑: 建造住宅/商业/工业/公园 (消耗建筑资源+资金)")
        print("  • 点击地图格子: 建造或清除建筑")
        print("=" * 50)
        
        if background:
            server_thread = threading.Thread(target=self.server.serve_forever, daemon=True)
            server_thread.start()
            print("服务器已在后台运行")
        else:
            try:
                print("按 Ctrl+C 停止游戏服务器")
                print("=" * 50)
                self.server.serve_forever()
            except KeyboardInterrupt:
                print("\n游戏服务器已停止")
    
    def stop(self):
        """停止游戏服务器"""
        if self.server:
            self.server.shutdown()
            print("游戏服务器已停止")


def main():
    """主函数"""
    print("正在启动城市建造游戏...")
    game_server = CityGameServer(port=8086)
    game_server.start(background=False)


if __name__ == "__main__":
    main()
